package cn.legend.travel.admin.comment.config;

import cn.legend.travel.admin.comment.filter.JwtAuthorizationFilter;
import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.web.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final JwtAuthorizationFilter authorizationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();

        http.exceptionHandling().authenticationEntryPoint((request, response, e) -> {
            JsonResult fail = JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED, "你当前未登录,请先登录");
            String jsonString = JSON.toJSONString(fail);
            response.setContentType("application/json; charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
        });

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authorizationFilter, UsernamePasswordAuthenticationFilter.class);

        http.csrf().disable();

        String[] urls = {
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/swagger-resources",
                "/v2/api-docs"
        };

        http.authorizeRequests() //配置请求授权
                //.mvcMatchers("/mall/goods/add-new").hasAnyAuthority("发布商品的权限")
                //.mvcMatchers("/mall/goods/*/delete").hasAnyAuthority("删除商品的权限")
                //.mvcMatchers("/mall/goods/*/check").hasAnyAuthority("审核商品的权限")
                //.mvcMatchers("/mall/goods/*/edit").hasAnyAuthority("编辑商品的权限")
                .mvcMatchers(urls)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
}
